<template>
	<view v-if="Detail!=null">
		<cu-custom bgColor="theme-bg-color fixed" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content"><text>{{Detail.Name}}</text></block>
		</cu-custom>
		
		<!-- 九宫格手势签到界面 -->
		<view class="gesture-container">
			<view class="gesture-title">请绘制手势图案完成签到</view>
			
			<view class="gesture-grid">
				<!-- 九宫格点阵 -->
				<view class="grid-row" v-for="row in 3" :key="'row-'+row">
					<view class="grid-dot" v-for="col in 3" :key="'dot-'+((row-1)*3+col)" 
						:class="{active: isPointActive((row-1)*3+col)}">
						{{(row-1)*3+col}}
					</view>
				</view>
				
				<!-- 手势绘制画布 -->
				<canvas canvas-id="gestureCanvas" class="gesture-canvas" 
					@touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
			</view>
			
			<!-- 提示信息 -->
			<view class="gesture-info" :class="{' text-red': patternError}">
				{{patternMessage || '请至少连接4个点完成签到'}}
			</view>
		</view>
		
		<!-- 底部打卡按钮 -->
		<view class="fixed-bottom" >
			<view class="flex  margin-top-xs align-center justify-center">
				<view class="click-item " :class="isAllowCricle==false?'bg-gray text-black':'bg-blue' " @click="SumbitClock">
					<text class="text-bold tex-lg" :class="isAllowCricle==false?' text-black':'text-white' "
						:disabled="isAllowCricle">手势签到</text>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	import store from "@/store";
	import BigNumber from '@/utils/bignumber.js'
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				showCamera: false, // 控制摄像头显示
				Detail: null,
				CheckSetting: {},
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				keyword: '直接签到',
				polyline: [{
					points: [],
					color: '#FF0000AA', // 多边形颜色
					width: 10, // 多边形宽度
					dottedLine: true // 是否为虚线
				}],
				polygon: [{
					strokeWidth: "2",
					strokeColor: "#FF0000AA",
					fillColor: '#FF0000AA', // 多边形颜色
				}],
				allLines: [],
				circles: [],
				markers: [],
				isAllowCricle: true,
				time: 0,
				distance: 0,
				ClockInfo: null,
				CheckSettingId: 0,
				// 九宫格手势相关数据
				currentPattern: [], // 当前绘制的图案
				patternMessage: '', // 图案提示信息
				patternError: false, // 图案错误标志
				activePoints: [], // 激活的点
				canvasContext: null, // canvas上下文
				gridPoints: [], // 九宫格点位置信息
				isTouching: false // 是否正在触摸
			}
		},
		computed: {
			...mapGetters(["userInfo", "userId", "location"]),
		},
		onLoad(option) {
			// 打印请求参数CheckSettingId
			console.log("CheckSettingId", option.checkSettingId);
			this.CheckSettingId = option.checkSettingId;
			this.GetCheckSetting();
		},
		onShow() {
			this.GetOrganizationApi();
		},
		onHide() {
		},
		onUnload() {
		},
		onReady() {
			// 初始化手势九宫格
			this.$nextTick(() => {
				this.initGestureCanvas();
			});
		},
		methods: {
			//得到打卡状态
			async GetClockInfoApi() {
				let {
					Data
				} = await this.$http.PostAsync("/CheckRecord/GetClockInfo", {
					OrganizationId: this.userInfo.OrganizationId,
					UserId: this.userInfo.Id
				});
				this.ClockInfo = Data;
			},
			// 初始化手势Canvas
			initGestureCanvas() {
				// 获取canvas上下文
				this.canvasContext = uni.createCanvasContext('gestureCanvas', this);
				
				// 计算九宫格点的位置
				const query = uni.createSelectorQuery().in(this);
				query.select('.gesture-grid').boundingClientRect(data => {
					if (!data) return;
					
					const width = data.width;
					const height = data.height;
					const dotSize = Math.min(width, height) / 6; // 点的大小
					const padding = dotSize; // 边距
					
					// 计算每个点的位置
					this.gridPoints = [];
					for (let row = 0; row < 3; row++) {
						for (let col = 0; col < 3; col++) {
							const index = row * 3 + col + 1; // 从1开始编号
							const x = padding + col * ((width - padding * 2) / 2);
							const y = padding + row * ((height - padding * 2) / 2);
							this.gridPoints.push({
								index,
								x: x + dotSize / 2,
								y: y + dotSize / 2,
								radius: dotSize / 2
							});
						}
					}
				}).exec();
			},
			// 检查点是否被激活
			isPointActive(index) {
				return this.currentPattern.includes(index);
			},
			// 获取触摸点对应的九宫格点
			getTouchedPoint(x, y) {
				for (const point of this.gridPoints) {
					const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2));
					if (distance < point.radius * 1.5) {
						return point;
					}
				}
				return null;
			},
			// 触摸开始事件
			touchStart(e) {
				if (this.isTouching) return;
				
				this.isTouching = true;
				this.currentPattern = [];
				this.activePoints = [];
				this.patternMessage = '';
				this.patternError = false;
				
				const touch = e.touches[0];
				const point = this.getTouchedPoint(touch.x, touch.y);
				
				if (point) {
					this.currentPattern.push(point.index);
					this.activePoints.push(point);
					
					// 绘制激活的点
					this.drawPattern();
				}
			},
			// 触摸移动事件
			touchMove(e) {
				if (!this.isTouching) return;
				
				const touch = e.touches[0];
				const point = this.getTouchedPoint(touch.x, touch.y);
				
				if (point && !this.currentPattern.includes(point.index)) {
					this.currentPattern.push(point.index);
					this.activePoints.push(point);
				}
				
				// 重新绘制图案
				this.drawPattern(touch.x, touch.y);
			},
			// 触摸结束事件
			touchEnd(e) {
				if (!this.isTouching) return;
				
				this.isTouching = false;
				
				// 验证图案
				if (this.currentPattern.length < 4) {
					this.patternMessage = '至少连接4个点，请重试';
					this.patternError = true;
					setTimeout(() => {
						this.resetPattern();
					}, 1500);
				} else {
					// 验证成功，提交签到
					this.submitGesturePattern();
				}
				
				// 最后一次绘制图案（不带当前触摸点）
				this.drawPattern();
			},
			// 绘制图案
			drawPattern(currentX, currentY) {
				if (!this.canvasContext) return;
				
				// 清除画布
				this.canvasContext.clearRect(0, 0, 1000, 1000);
				
				// 设置线条样式
				this.canvasContext.setStrokeStyle('#007AFF');
				this.canvasContext.setLineWidth(3);
				this.canvasContext.setLineCap('round');
				this.canvasContext.setLineJoin('round');
				
				// 绘制已连接的线
				if (this.activePoints.length > 0) {
					this.canvasContext.beginPath();
					this.canvasContext.moveTo(this.activePoints[0].x, this.activePoints[0].y);
					
					for (let i = 1; i < this.activePoints.length; i++) {
						this.canvasContext.lineTo(this.activePoints[i].x, this.activePoints[i].y);
					}
					
					// 如果有当前触摸点，连接到当前触摸点
					if (currentX && currentY) {
						this.canvasContext.lineTo(currentX, currentY);
					}
					
					this.canvasContext.stroke();
				}
				
				// 绘制激活的点
				for (const point of this.activePoints) {
					this.canvasContext.beginPath();
					this.canvasContext.arc(point.x, point.y, point.radius / 2, 0, Math.PI * 2);
					this.canvasContext.setFillStyle('#007AFF');
					this.canvasContext.fill();
				}
				
				// 提交绘制
				this.canvasContext.draw(false);
			},
			// 重置图案
			resetPattern() {
				this.currentPattern = [];
				this.activePoints = [];
				this.patternMessage = '';
				this.patternError = false;
				
				// 清除画布
				if (this.canvasContext) {
					this.canvasContext.clearRect(0, 0, 1000, 1000);
					this.canvasContext.draw(true);
				}
			},
			// 提交手势图案
			async submitGesturePattern() {
				if (this.isAllowCricle == false) {
					uni.showToast({
						title: "已签到",
						icon: "none",
						duration: 2000
					});
					return;
				}
				
				try {
					// 将手势图案转换为字符串
					const gesturePattern = this.currentPattern.join('');
					
					// 调用签到接口
					let {
						Success,
						Message
					} = await this.$http.PostAsync("/CheckRecord/Check", {
						UserId: this.userInfo.Id,
						OrganizationId: this.userInfo.OrganizationId,
						CheckSettingId: this.CheckSettingId,
						CheckType: "gesture",
						GesturePattern: gesturePattern
					});
					
					if (Success) {
						uni.showToast({
							title: "签到成功",
							icon: "success",
							duration: 2000
						});
						this.isAllowCricle = false;
						this.keyword = "已打卡";
						this.patternMessage = "签到成功";
						this.patternError = false;
					} else {
						uni.showToast({
							title: Message || "签到失败",
							icon: "none",
							duration: 2000
						});
						this.patternMessage = Message || "签到失败";
						this.patternError = true;
						setTimeout(() => {
							this.resetPattern();
						}, 1500);
					}
				} catch (error) {
					console.error('手势签到错误:', error);
					uni.showToast({
						title: "签到异常",
						icon: "none",
						duration: 2000
					});
					this.patternMessage = "签到异常，请重试";
					this.patternError = true;
					setTimeout(() => {
						this.resetPattern();
					}, 1500);
				}
			},
			//打卡提交（旧的扫码方式，保留作为备用）
			async SumbitClock() {
				if(this.isAllowCricle == false){
					uni.showToast({
						title: "已签到",
						icon: "none",
						duration: 2000
					});
					return;
				}

				try {
					// 打开摄像头扫描二维码，得到扫码后的内容
					const [error, res] = await uni.scanCode({
						onlyFromCamera: true,
						scanType: ['qrCode']
					});

					if (error) {
						uni.showToast({
							title: "扫码失败",
							icon: "none",
							duration: 2000
						});
						return;
					}

					// 获取扫码结果
					const qrContent = res.result;

					console.log('扫码结果:', qrContent);
					console.log('CheckSetting.CheckContent:', this.CheckSetting.CheckContent);

					// 判断扫码结果是否和后台相同
					if(qrContent != this.CheckSetting.CheckContent){
						uni.showToast({
							title: "二维码不匹配",
							icon: "none",
							duration: 2000
						});
						return;
					}

					// 调用签到接口
					let {
						Success,
						Message
					} = await this.$http.PostAsync("/CheckRecord/Check", {
						UserId: this.userInfo.Id,
						OrganizationId: this.userInfo.OrganizationId,
						CheckSettingId: this.CheckSettingId,
						CheckType: "qrcode",
						QrContent: qrContent
					});
				if (Success) {
					uni.showToast({
						title: "签到成功",
						icon: "success",
						duration: 2000
					});
					this.isAllowCricle = false;
					this.keyword = "已打卡";
					//uni.navigateBack();
				} else {
					uni.showToast({
						title: Message || "签到失败",
						icon: "none",
						duration: 2000
					});
				}
				} catch (error) {
					console.error('扫码签到错误:', error);
					uni.showToast({
						title: "签到异常",
						icon: "none",
						duration: 2000
					});
				}
			},
			//得到班级信息
			async GetOrganizationApi() {
				let {
					Data
				} = await this.$http.PostAsync("/Organization/Get", {
					Id: this.userInfo.OrganizationId
				});
				this.Detail = Data;
			},
			async GetCheckSetting() {
				let {
					Data
				} = await this.$http.PostAsync("/CheckSetting/GetOne", {
					Id: this.CheckSettingId
				});
				this.CheckSetting = Data;
			}
		}
	}
</script>
<style>
	.fixed-center {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 9999;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.cur {
		background-color: #0065B7 !important;
		color: white;
		border-radius: 10upx;
	}

	.click-item {
		width: 200upx;
		height: 200upx;
		border-radius: 50%;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	/* 九宫格手势密码样式 */
	.gesture-container {
		padding: 30rpx;
		margin-top: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.gesture-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
		color: #333;
	}
	
	.gesture-grid {
		position: relative;
		width: 600rpx;
		height: 600rpx;
		background-color: #f8f8f8;
		border-radius: 20rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
	}
	
	.gesture-canvas {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 10;
	}
	
	.grid-row {
		display: flex;
		justify-content: space-around;
		height: 33.33%;
	}
	
	.grid-dot {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background-color: #e0e0e0;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 30rpx;
		position: relative;
		z-index: 5;
	}
	
	.grid-dot.active {
		background-color: #007AFF;
		color: white;
	}
	
	.gesture-info {
		margin-top: 40rpx;
		font-size: 32rpx;
		color: #666;
		height: 80rpx;
		text-align: center;
	}
	
	.text-red {
		color: #FF3B30;
	}
	/* 新增相机界面样式 */
		.camera-container {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100vh;
			background-color: #000;
			z-index: 9999;
		}
		
		.camera-buttons {
			position: fixed;
			bottom: 50px;
			left: 0;
			width: 100%;
			display: flex;
			justify-content: space-around;
			padding: 0 20px;
		}
		
		.btn-capture {
			background-color: #007AFF;
			color: white;
			border-radius: 50px;
			padding: 10px 30px;
		}
		
		.btn-cancel {
			background-color: #FF3B30;
			color: white;
			border-radius: 50px;
			padding: 10px 30px;
		}
		
		/* 原有样式保持不变 */
		.fixed-bottom {
			position: fixed;
			width: 100%;
			padding: 20upx;
			bottom: 0;
			left: 0;
			z-index: 9999;
			background-color: white;
		}
		
		.cur {
			background-color: #0065B7 !important;
			color: white;
			border-radius: 10upx;
		}
		
		.click-item {
			width: 200upx;
			height: 200upx;
			border-radius: 50%;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
		}
</style>